package com.gec.oasys.realm;

import com.gec.oasys.pojo.SysMenu;
import com.gec.oasys.pojo.SysUser;
import com.gec.oasys.service.SysMenuService;
import com.gec.oasys.service.SysUserService;
import com.gec.oasys.utils.SysConstanst;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class OaSysRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    //授权
    /*
    * getPrimaryPrincipal中存入对象信息
    * addRole中为角色名字
    * addStringPermission为添加权限
    * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser su=(SysUser)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(su.getRoleName());

        List<SysMenu> sysMenuList=sysMenuService.findMenuPermssionByRoleId(su.getRoleId());
        for (SysMenu sysMenu:sysMenuList){
            String permission =sysMenu.getPermission();
            simpleAuthorizationInfo.addStringPermission(permission);
        }

        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;

        String inputUserName=usernamePasswordToken.getUsername();

        String inputPassword=new String(usernamePasswordToken.getPassword());

        String passwordMd5=new Md5Hash(inputPassword, SysConstanst.SALT,SysConstanst.HASHITERATIONS).toString();

        SysUser sysUser=new SysUser();
        sysUser.setLoginName(inputUserName);
        sysUser.setPwd(passwordMd5);
        List<SysUser> sysUserList= sysUserService.findUserByLoginNameAndPwd(sysUser);

        if(sysUserList!=null && sysUserList.size()>0){
            SysUser outSysUser=sysUserList.get(0);
//String.valueOf(outSysUser.getId())
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
                    outSysUser,
                    inputPassword,
                    "OaSysRealm"
            );
            return simpleAuthenticationInfo;
        }else{
            throw new AuthenticationException("认证失败");
        }
    }
}
